package com.magicsoft.share.ui.my;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.magicsoft.share.R;
import com.magicsoft.share.adapter.article.EditArticleAdapter;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.article.ArticleContent;
import com.magicsoft.share.bean.article.MyArticleDetail;
import com.magicsoft.share.constant.AppDavikActivityMgr;
import com.magicsoft.share.constant.Constant;
import com.magicsoft.share.customview.alertview.AlertView;
import com.magicsoft.share.customview.alertview.OnItemClickListener;
import com.magicsoft.share.presenter.article.AddArticlePresenter;
import com.magicsoft.share.ui.article.CoverActivity;
import com.magicsoft.share.ui.article.CropImageActivity;
import com.magicsoft.share.ui.article.EdtContentActivity;
import com.magicsoft.share.ui.article.EdtTitleActivity;
import com.magicsoft.share.utils.OssManager;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.article.IAddArticleView;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.swipe.touch.OnItemMovementListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.util.Log.d;

public class ArticleEdtActivity extends BaseActivity<IAddArticleView, AddArticlePresenter> implements IAddArticleView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView mRecyclerView;
    private EditArticleAdapter articleAdapter;
    private ImageView iv_pop;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            iv_pop.setVisibility(View.GONE);
        }
    };
    private int mClickPosition;
    private ImageView iv_cover;

    private String coverStr;
    private String coverRiginalStr;
    private TextView tv_article_title;
    private String contentStr;
    private List<LocalMedia> selectList;
    private OssManager ossManager;
    private long articleId;


    @Override
    public AddArticlePresenter initPresenter() {
        return new AddArticlePresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_article_edt;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        tvTitle.setText("编辑");
        tvRight.setText("完成");
        ossManager = OssManager.getInstance().init(this);

        initRV();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    Message obtain = Message.obtain();
                    handler.sendMessage(obtain);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
       int  articleId1 = getIntent().getIntExtra("Data", -1);
        Log.e("articleId", "onClick111: " + articleId1);

        mPresenter.myArticleDetail((long) articleId1);
    }
//此处修改
    @Override
    public void requestData() {

    }


    @OnClick({R.id.ibtn_left, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_left:
                initDialog();
                break;
            case R.id.tv_right:
                contentStr = new Gson().toJson(articleAdapter.getData());
                mPresenter.articleEdit(articleId, tv_article_title.getText().toString(), coverStr, coverRiginalStr, contentStr, null, null, null, null, 1);
                break;
        }
    }


    private void initDialog() {
        new AlertView.Builder().setContext(this).setTitle("是否存为草稿？").setStyle(AlertView.Style.Alert).setCancelText("存为草稿").setOthers(new String[]{"撤销编辑"}).setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {

                if (position == -1) {
                    contentStr = new Gson().toJson(articleAdapter.getData());
                    mPresenter.articleEdit(articleId, tv_article_title.getText().toString(), coverStr, coverRiginalStr, contentStr, null, null, null, null, 2);
                } else {
                    finish();
                }
            }
        }).build().show();
    }

    private void initRV() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        articleAdapter = new EditArticleAdapter(R.layout.item_edt_article, new ArrayList<ArticleContent>());
        articleAdapter.setNewData(new ArrayList<ArticleContent>());

        articleAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                d("lyf", "onItemChildClick: " + position);
                position = position - mRecyclerView.getHeaderItemCount();

                switch (view.getId()) {
                    case R.id.iv_add_img:

                        mClickPosition = position;
                        addPhoto();
                        break;
                    case R.id.iv_add_text:
                        mClickPosition = position;
                        startActivityForResult(new Intent(ArticleEdtActivity.this, EdtContentActivity.class), Constant.REQUEST_ARTICLE_ADD_CONTENT);
                        break;
                    case R.id.iv_add:
                        articleAdapter.addShowOrHide(position);
                        break;
                    case R.id.imageView:
                        mClickPosition = position;
                        Intent intent1 = new Intent(ArticleEdtActivity.this, CropImageActivity.class);
                        intent1.putExtra("imgUrl", articleAdapter.getItem(position).getImg());
                        startActivityForResult(intent1, Constant.REQUEST_ARTICLE_IMG);
                        break;
                        //修改标题
                    case R.id.tv_content:
                        mClickPosition = position;
                        Intent intent = new Intent(ArticleEdtActivity.this, EdtContentActivity.class);
                        intent.putExtra("contentStr", articleAdapter.getItem(position).getContent());
                        startActivityForResult(intent, Constant.REQUEST_ARTICLE_CONTENT);
                        break;
                    case R.id.iv_close:
                        if (articleAdapter.getData().size() == 1) {
                            ToastUtils.showToast(ArticleEdtActivity.this, "至少保留一张图片");
                        } else {
                            articleAdapter.remove(position);
                        }
                        break;
                    default:
                        break;
                }
            }
        });


        View view = LayoutInflater.from(this).inflate(R.layout.top_edt_article, mRecyclerView, false);
        iv_pop = view.findViewById(R.id.iv_pop);
        iv_cover = view.findViewById(R.id.iv_cover);
        Glide.with(this).load(coverRiginalStr).into(iv_cover);
        iv_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ArticleEdtActivity.this, CoverActivity.class);
                intent.putExtra("coverRiginalStr", coverRiginalStr);
                startActivityForResult(intent, Constant.REQUEST_ARTICLE_COVER);
            }
        });
        tv_article_title = view.findViewById(R.id.tv_article_title);
        tv_article_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ArticleEdtActivity.this, EdtTitleActivity.class);
                intent.putExtra("titleStr", tv_article_title.getText().toString());
                startActivityForResult(intent, Constant.REQUEST_ARTICLE_TITLE);
            }
        });

        mRecyclerView.addHeaderView(view);
        mRecyclerView.setAdapter(articleAdapter);
        mRecyclerView.setLongPressDragEnabled(true);

        mRecyclerView.setOnItemMovementListener(mItemMovementListener);
        mRecyclerView.setOnItemMoveListener(new OnItemMoveListener() {

            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                // TODO 如何让不同的ViewType之间可以拖拽，就是去掉这个判断。
                if (srcHolder.getItemViewType() != targetHolder.getItemViewType()) {
                    return false;
                }

                // 添加了HeadView时，通过ViewHolder拿到的position都需要减掉HeadView的数量。
                int fromPosition = srcHolder.getAdapterPosition() - mRecyclerView.getHeaderItemCount();
                int toPosition = targetHolder.getAdapterPosition() - mRecyclerView.getHeaderItemCount();

//                        if (toPosition == 0) {// 保证第一个不被挤走。
//                            return false;
//                        }
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(articleAdapter.getData(), i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(articleAdapter.getData(), i, i - 1);
                    }
                }

                articleAdapter.notifyItemMoved(fromPosition, toPosition);

                return true;// 返回true表示处理了并可以换位置，返回false表示你没有处理并不能换位置。
            }

            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
                int position = srcHolder.getAdapterPosition() - mRecyclerView.getHeaderItemCount();
                articleAdapter.getData().remove(position);
                articleAdapter.notifyItemRemoved(position);
                //  Toast.makeText(DefineActivity.this, "现在的第" + position + "条被删除。", Toast.LENGTH_SHORT).show();
            }
        });

    }


    /**
     * Item移动参数回调监听，这里自定义Item怎样移动。
     */
    private OnItemMovementListener mItemMovementListener = new OnItemMovementListener() {
        @Override
        public int onDragFlags(RecyclerView recyclerView, RecyclerView.ViewHolder targetViewHolder) {
            int adapterPosition = targetViewHolder.getAdapterPosition();
            if (adapterPosition == 0) { // 这里让HeaderView不能拖拽。
                return OnItemMovementListener.INVALID;// 返回无效的方向。
            }

            // 真实的Position：通过ViewHolder拿到的position都需要减掉HeadView的数量。
            int position = adapterPosition - mRecyclerView.getHeaderItemCount();

            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager) {
                // Grid可以上下左右拖拽。
                return OnItemMovementListener.LEFT |
                        OnItemMovementListener.UP |
                        OnItemMovementListener.RIGHT |
                        OnItemMovementListener.DOWN;
            } else if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;

                // 横向List只能左右拖拽。
                if (linearLayoutManager.getOrientation() == LinearLayoutManager.HORIZONTAL) {
                    return (OnItemMovementListener.LEFT | OnItemMovementListener.RIGHT);
                }
                // 竖向List只能上下拖拽。
                else {
                    return OnItemMovementListener.UP | OnItemMovementListener.DOWN;
                }
            }
            return OnItemMovementListener.INVALID;// 返回无效的方向。
        }

        @Override
        public int onSwipeFlags(RecyclerView recyclerView, RecyclerView.ViewHolder targetViewHolder) {
            int adapterPosition = targetViewHolder.getAdapterPosition();
            if (adapterPosition == 0) { // 这里让HeaderView不能侧滑删除。
                return OnItemMovementListener.INVALID;// 返回无效的方向。
            }

            // 真实的Position：通过ViewHolder拿到的position都需要减掉HeadView的数量。
            int position = adapterPosition - mRecyclerView.getHeaderItemCount();

            // 假如让普通Item的第一个不能侧滑删除。
            if (position == 0) {
                return OnItemMovementListener.INVALID;// 返回无效的方向。
            }

            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager) {
                LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                // 横向Grid上下侧滑。
                if (manager.getOrientation() == LinearLayoutManager.HORIZONTAL) {
                    return ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                }
                // 竖向Grid左右侧滑。
                else {
                    return ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                }
            } else if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                // 横向List上下侧滑。
                if (manager.getOrientation() == LinearLayoutManager.HORIZONTAL) {
                    return OnItemMovementListener.UP | OnItemMovementListener.DOWN;
                }
                // 竖向List左右侧滑。
                else {
                    return OnItemMovementListener.LEFT | OnItemMovementListener.RIGHT;
                }
            }
            return OnItemMovementListener.INVALID;// 其它均返回无效的方向。
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("SLL:","返回成功!"+requestCode);
        if (data != null) {
            switch (requestCode) {

                case PictureConfig.CHOOSE_REQUEST:
                    ToastUtils.showToast(this,"返回成功!");
                    // 图片选择结果回调
                    Log.e("data", "lalalla");
                    selectList = PictureSelector.obtainMultipleResult(data);

                    ArrayList<String> strings = new ArrayList<>();

                    for (int i = 0; i < selectList.size(); i++) {
                        strings.add(selectList.get(i).getCompressPath());
                        d("pick", "onActivityResult: " + i + selectList.get(i).getCompressPath());
                    }
                    ossManager.refresh();
                    ossManager.upload(strings, new OssManager.uploadListener() {
                        @Override
                        public void onSuccess(ArrayList<String> url) {
                            ArrayList<ArticleContent> articleContents = new ArrayList<>();
                            for (int i = 0; i < url.size(); i++) {
                                ArticleContent articleContent = new ArticleContent();
                                articleContent.setImg(url.get(i));
                                articleContents.add(articleContent);
                            }
                            articleAdapter.addData(mClickPosition + 1, articleContents);

                        }

                        @Override
                        public void onFail() {
                            d("pick", "onFail: ");
                        }
                    });

                    break;
                case Constant.REQUEST_ARTICLE_TITLE:
                    String articleStr = data.getStringExtra("titleStr");
                    tv_article_title.setText(articleStr);
                    Log.e("dataarticleStr", articleStr);
                    break;
                case Constant.REQUEST_ARTICLE_CONTENT:
                    String contentStr = data.getStringExtra("contentStr");
                    d("lyf", "onActivityResult: " + contentStr);

                    articleAdapter.getItem(mClickPosition).setContent(contentStr);
                    articleAdapter.notifyItemChanged(mClickPosition);
                    break;
                case Constant.REQUEST_ARTICLE_ADD_CONTENT:
                    String addContentStr = data.getStringExtra("contentStr");
                    Log.e("data", addContentStr);
                    ArticleContent articleContent = new ArticleContent();
                    articleContent.setContent(addContentStr);
                    articleAdapter.addData(mClickPosition + 1, articleContent);
                    break;
                case Constant.REQUEST_ARTICLE_COVER:

                    coverRiginalStr = data.getStringExtra("coverRiginalStr");
                    coverStr = data.getStringExtra("coverStr");
                    Log.d("lyf", "onActivityResult: " + coverStr);
                    Glide.with(this).load(coverStr).into(iv_cover);
                    break;
                case Constant.REQUEST_ARTICLE_IMG:
                    String imgUrlStr = data.getStringExtra("imgUrlStr");
                    articleAdapter.getItem(mClickPosition).setImg(imgUrlStr);
                    articleAdapter.notifyItemChanged(mClickPosition);
                    break;
                default:
                    break;
            }
        }

    }
    private void addPhoto() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(ArticleEdtActivity.this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(20)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                // .previewVideo()// 是否可预览视频 true or false
                // .enablePreviewAudio() // 是否可播放音频 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                // .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                //    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                //     .enableCrop()// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                //  .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //  .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(true)// 是否显示gif图片 true or false
                //.compressSavePath("/CustomPath")//压缩图片保存地址
                //   .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                //   .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                //    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                //   .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                //     .selectionMedia(false)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                //   .minimumCompressSize(100)// 小于100kb的图片不压缩
                //    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                //   .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                //  .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                //   .videoQuality()// 视频录制质量 0 or 1 int
                // .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                //  .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    public void articleEditSuccess() {
        ToastUtils.showToast(this, "文章修改成功");
        AppDavikActivityMgr.getScreenManager().finishActivity(AllShareActivity.class);
        AppDavikActivityMgr.getScreenManager().finishActivity(ArticleShareActivity.class);
        Intent intent = new Intent(this, AllShareActivity.class);
        intent.putExtra("position", 0);
        startActivity(intent);
        finish();
    }

    @Override
    public void myArticleDetailSuccess(MyArticleDetail data) {
        articleId = data.getArticle_id();
        coverStr = data.getCover();
//        Log.e("details","执行");
        Glide.with(this).load(coverStr).into(iv_cover);
        coverRiginalStr = data.getCover_riginal();
        tv_article_title.setText(data.getTitle());
        articleAdapter.setNewData(data.getContent());
    }

    @Override
    public void deleteArticleSuccess() {

    }


}
